package com.xs.ai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDate;


/**
 * @author xushu
 * @version 1.0
 * @description:
 */
@RestController
@CrossOrigin
public class OpenAiController {

    ChatClient chatClient;

    public OpenAiController(ChatClient.Builder builder, ChatMemory chatMemory,VectorStore vectorStore) {
        this.chatClient = builder
                .defaultSystem(//预设角色
                        """
                                您是“XuShu”航空公司的客户聊天⽀持代理。请以友好、乐于助⼈
                                且愉快的⽅式来回复。
                                 您正在通过在线聊天系统与客户互动。
                                 在提供有关预订或取消预订的信息之前，您必须始终
                                 从⽤户处获取以下信息：预订号、客户姓名。
                                 在询问⽤户之前，请检查消息历史记录以获取此信息。
                                 进行退订之前需用户二次确认。
                                 请讲中⽂。
                                 今天的⽇期是 {current_date}.
                                """
                )
                .defaultAdvisors(//拦截器:记忆对话
                        new PromptChatMemoryAdvisor(chatMemory),
                        new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults())
                )
                .defaultFunctions(//
                        "cancelBooking","getBookingDetails"
                )
                .build();
    }

    @CrossOrigin
    @GetMapping(value = "/ai/generateStreamAsString", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStreamAsString(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
        Flux<String> content = chatClient
                .prompt()
                .system(a -> a.param("current_date", LocalDate.now().toString()))
                .user(message)
                .stream().content();
        return content.concatWith(Flux.just("[complete]"));
    }
}
